﻿using System;
using System.Windows.Forms;
using DbManager;
using DbManager.DataManager;
using DbManager.QueryBuilder.DataManagment.Options;

namespace TAProject.UI.Options
{
    public partial class FormOptions : FormTemplate
    {
        private readonly Form _parentForm;
        private readonly IConnectionManager _connectionManager;
        private readonly IDataManager _dataManager;

        private IDataManagmentOptions _dataManagmentInsurance;
        private IDataManagmentOptions _dataManagmentDiscount;

        public FormOptions(Form parentForm, IConnectionManager connectionManager, IDataManager dataManager):base(parentForm)
        {
            InitializeComponent();

            _parentForm = parentForm;
            _connectionManager = connectionManager;
            _dataManager = dataManager;

            _parentForm.Enabled = false;
            FillForm();
        }

        private void ButtonCancelClick(object sender, EventArgs e)
        {
            FormClose();
        }

        private void FormClose()
        {
            _parentForm.Enabled = true;
            Close();
        }

        private void FillForm()
        {
            _dataManagmentInsurance = new DataManagmentInsurance();
            _dataManagmentDiscount = new DataManagmentDiscount();
            
            TryGetData(textBoxInsurance, _dataManagmentInsurance);
            TryGetData(textBoxDiscount, _dataManagmentDiscount);
        }

        private void TryGetData(Control textBox, IDataManagmentOptions dataManagmentOptions)
        {
            var value = _dataManager.GetItemStringById(dataManagmentOptions.GetSelectQuery(),
                                                           _connectionManager.GetConnection());

            if (!string.IsNullOrEmpty(value))
            {
                try
                {
                    textBox.Text = (double.Parse(value.Replace(".", ",")) * 100).ToString();
                }
                catch (Exception)
                {
                    MessageBox.Show("Ошибка распознавания данных.");
                }
            }
            else
            {
                MessageBox.Show("Ошибка получения данных из БД");
                FormClose();
            }
        }

        private void ButtonSaveClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBoxDiscount.Text) && !string.IsNullOrEmpty(textBoxInsurance.Text))
            {
                var isSuccessful = TryToSaveData("страховка", textBoxInsurance, _dataManagmentInsurance);
                isSuccessful = TryToSaveData("скидка", textBoxDiscount, _dataManagmentDiscount);
                if (isSuccessful)
                {
                    MessageBox.Show("Настройки сохранены успешно.");
                    FormClose();
                }
            }
            else
            {
                MessageBox.Show("Не все поля заполнены.");
            }
        }

        private bool TryToSaveData(string whatSave, Control textBox, IDataManagmentOptions dataManagmentOptions)
        {
            double value;

            try
            {
                value = double.Parse(textBox.Text.Replace(".", ",")) / 100;
            }
            catch (Exception)
            {
                MessageBox.Show("Данные \""+whatSave+"\" введены не корректно");
                return false;
            }

            var affected = _dataManager.ManageDataInDb(dataManagmentOptions.GetUpdateQuery(value),
                                                       _connectionManager.GetConnection());
            if (affected == 0)
            {
                MessageBox.Show("Ошибка сохранения данных \""+whatSave+"\".");
                return false;
            }
            return true;
        }
    }
}
